package cn.map.service.impl;

import cn.map.constants.Constant;
import cn.map.entity.RsaResult;
import cn.map.service.RsaService;
import cn.map.utils.encryption.*;
import com.alibaba.fastjson.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 後溪
 */
@Service
public class RsaServiceImpl implements RsaService {

    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public String getPublicKey(String serverPublicKey) {
        String[] split = serverPublicKey.split("-");
        serverPublicKey = split[0];
        String publicKey = "";
        try {
            Map<String, String> localKeys = RSA.generateKeyPair();
            publicKey = localKeys.get("publicKey");
            if(serverPublicKey!=null){
                redisTemplate.opsForValue().set("SERVER_PUBLIC_KEY-"+split[1],serverPublicKey);
                redisTemplate.opsForValue().set("EQUIPMENT_PUBLIC_KEY-"+split[1],publicKey);
                redisTemplate.opsForValue().set("EQUIPMENT_PRIVATE_KEY-"+split[1],localKeys.get("privateKey"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return publicKey;
    }

    @Override
    public int uploadCoupons(String dataJson) {
        String[] split = dataJson.split("-");
        dataJson = split[0];
        System.out.println("原始数据：：："+dataJson.replaceAll(" ","+"));
        HashMap<String,String> hashMap = JSONObject.parseObject(dataJson.replaceAll(" ","+"), HashMap.class);
        String serverPublicKey = String.valueOf(redisTemplate.opsForValue().get("SERVER_PUBLIC_KEY-"+split[1]));
        String privateKey = String.valueOf(redisTemplate.opsForValue().get("EQUIPMENT_PRIVATE_KEY-"+split[1]));

        int code = 0;
        try {
            boolean passSign = EncryUtil.checkDecryptAndSign(hashMap.get("dataJson"),
                    hashMap.get("encryptKey"), serverPublicKey, privateKey);

            if(passSign){
                String aesKey = RSA.decrypt(hashMap.get("encryptKey"),
                        privateKey);
                String data = ConvertUtils.hexStringToString(AES.decryptFromBase64(hashMap.get("dataJson"),
                        aesKey));
                RsaResult rsaResult = JSONObject.parseObject(data, RsaResult.class);
                String message = rsaResult.getDataJson();
                System.err.println(message);
                code = 200;
            }
        } catch (Exception e) {
            e.printStackTrace();
            code = 500;
            return code;
        }
        return code;
    }


}
